package org.jeecg.modules.sxaq.utils.jpush;

import org.jeecg.modules.system.entity.SysUserDevice;
import org.jeecg.modules.system.service.ISysUserDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class JpushUtils {

    @Autowired
    private JiGuangPushService jiGuangPushService;

    @Autowired
    private ISysUserDeviceService sysUserDeviceService;

    public void push(String title, String alert, Map<String, String> extras){
        // 查询app_push字段是1的，需要进行推送。
        List<SysUserDevice> devices = sysUserDeviceService.getSysUserDeviceByAppPush();
        if (devices != null && devices.size() > 0) {
            List<String> tokensAndroid = new ArrayList<>();
            List<String> tokensIos = new ArrayList<>();
            for (SysUserDevice device : devices) {
                if (device.getClientType().equals("Android")) {
                    tokensAndroid.add(device.getPushToken());
                } else if (device.getClientType().equals("iOS")) {
                    tokensIos.add(device.getPushToken());
                }
            }
            PushBean pushBean = new PushBean();
            if (tokensAndroid.size() > 0) {
                pushBean.setTitle(title);
                pushBean.setAlert(alert);
                String[] tokens = tokensAndroid.toArray(new String[tokensAndroid.size()]);
                jiGuangPushService.pushAndroid(pushBean, tokens);
            }
            if (tokensIos.size() > 0) {
                pushBean.setAlert(title + "|||" + alert);
                String[] tokens = tokensIos.toArray(new String[tokensIos.size()]);
                jiGuangPushService.pushIos(pushBean, tokens);
            }
        }
    }
}
